<template>
  <BasicModal v-bind="$attrs" width="1000px" class="jnpf-flow-parameter-modal" @register="registerModal" title="查询配置" @ok="handleSubmit" destroyOnClose>
    <a-table :data-source="list" rowKey="id" :columns="getParameterColumns" size="small" :pagination="false" class="column-table">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'drag'">
          <i class="drag-handler icon-ym icon-ym-darg" title="点击拖动" />
        </template>
        <template v-if="column.key === 'vModel'">
          <JnpfTreeSelect
            v-model:value="record.vModel"
            placeholder="请选择"
            allowClear
            lastLevel
            lastLevelKey="children"
            :options="fieldOptions"
            :fieldNames="{ value: 'jnpfId' }"
            @change="(value:any, option:any) => handleChangeField(value, option, record, index)"
            class="!w-254px" />
        </template>
        <template v-if="column.key === 'label'">
          <a-input v-model:value="record.label" placeholder="请输入" allowClear :maxlength="50" />
        </template>
        <template v-if="column.key === 'type'">
          <JnpfSelect v-model:value="record.type" placeholder="请选择" :options="typeList" class="!w-160px" />
          <template v-if="canSetAttrs.includes(record.type)">
            <i class="icon-ym icon-ym-shezhi cursor-pointer ml-8px leading-30px" title="配置" @click="openExtraConfig(record, index)" />
          </template>
        </template>
        <template v-if="column.key === 'searchType'">
          <JnpfSelect v-model:value="record.searchType" :options="searchTypeOptions" />
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="link" danger @click="handleDel(index)"><i class="icon-ym icon-ym-app-delete"></i></a-button>
        </template>
      </template>
    </a-table>
    <div class="table-add-action" @click="handleAdd">
      <a-button type="link" preIcon="icon-ym icon-ym-btn-add">新增一行</a-button>
    </div>
    <ExtraConfigModal @register="registerExtraConfigModal" @confirm="updateRow" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { computed, nextTick, reactive, toRefs } from 'vue';
  import Sortablejs from 'sortablejs';
  import { cloneDeep } from 'lodash-es';
  import { buildUUID } from '@/utils/uuid';
  import { BasicModal, useModal, useModalInner } from '@/components/Modal';
  import ExtraConfigModal from '@/components/PrintDesign/PrintDesign/ExtraConfigModal.vue';
  import { useMessage } from '@/hooks/web/useMessage';

  const emit = defineEmits(['register', 'confirm']);

  interface State {
    queryList: any[];
    list: any[];
    fieldOptions: any[];
    activeIndex: number;
  }

  const state = reactive<State>({
    queryList: [],
    list: [],
    fieldOptions: [],
    activeIndex: 0,
  });
  const { list, fieldOptions } = toRefs(state);
  const [registerModal, { closeModal }] = useModalInner(init);
  const [registerExtraConfigModal, { openModal: openExtraConfigModal }] = useModal();
  const { createMessage } = useMessage();

  const canSetAttrs = ['select', 'date'];
  const columns = [
    { title: '拖动', dataIndex: 'drag', key: 'drag', align: 'center', width: 50 },
    { title: '字段', dataIndex: 'vModel', key: 'vModel', width: 270 },
    { title: '列名', dataIndex: 'label', key: 'label', width: 200 },
    { title: '输入类型', dataIndex: 'type', key: 'type', width: 200 },
    { title: '条件类型', dataIndex: 'searchType', key: 'searchType', width: 200 },
    { title: '操作', dataIndex: 'action', key: 'action', width: 80, align: 'center' },
  ];
  const searchTypeOptions = [
    { id: 1, fullName: '等于查询' },
    { id: 2, fullName: '模糊查询' },
    { id: 3, fullName: '范围查询' },
  ];
  const typeList = [
    { fullName: '输入框', id: 'input' },
    { fullName: '下拉选择', id: 'select' },
    // { fullName: '日期选择', id: 'date' },
  ];

  const getParameterColumns = computed(() => columns.map(o => ({ ...o, customCell: () => ({ class: 'align-top' }) })));

  function init(data: any) {
    state.queryList = data.queryList?.length ? cloneDeep(data.queryList) : [{ sheet: '', sheetName: '', queryList: [] }];
    state.list = cloneDeep(state.queryList[0].queryList);
    state.fieldOptions = cloneDeep(data.dataSetList ?? []);

    nextTick(() => {
      const columnTable: any = document.querySelector(`.column-table .ant-table-tbody`);
      Sortablejs.create(columnTable, {
        handle: '.drag-handler',
        animation: 150,
        easing: 'cubic-bezier(1, 0, 0, 1)',
        onStart: () => {},
        onEnd: ({ newIndex, oldIndex }: any) => {
          const currRow = state.list.splice(oldIndex, 1)[0];
          state.list.splice(newIndex, 0, currRow);
        },
      });
    });
  }

  function handleAdd() {
    state.list.push({
      id: buildUUID(),
      vModel: '',
      label: '',
      type: 'input',
      searchType: 2,
      config: { dataType: 'static', options: [], dictionaryType: '', propsValue: 'id', format: 'yyyy-MM-dd', precision: 0, thousands: false },
    });
  }
  function handleDel(index: number) {
    state.list.splice(index, 1);
  }
  function openExtraConfig(record: any, index: number) {
    state.activeIndex = index;
    openExtraConfigModal(true, { ...record });
  }
  function updateRow(data: any) {
    state.list[state.activeIndex] = data;
  }
  function handleChangeField(_: any, option: any, record: any, index: number) {
    const { label } = record;
    if (label !== '') {
      return;
    }
    const newRecord = {
      ...record,
      label: option?.label ?? '',
    };
    state.list[index] = { ...newRecord };
  }
  function handleSubmit() {
    const fileNames = new Set();

    for (let i = 0; i < state.list.length; i++) {
      const item = state.list[i];
      if (!item.vModel) {
        createMessage.warning(`第${i + 1}项的字段不能为空`);
        return;
      }

      if (!item.label) {
        createMessage.warning(`第${i + 1}项的列名不能为空`);
        return;
      }

      if (fileNames.has(item.vModel)) {
        createMessage.warning(`第${i + 1}项的字段重复`);
        return;
      }

      fileNames.add(item.vModel);
    }
    const queryList = [{ sheet: '', sheetName: '', queryList: state.list }];
    emit('confirm', queryList);
    nextTick(() => closeModal());
  }
</script>
<style lang="less">
  .jnpf-flow-parameter-modal {
    .ant-modal-body > .scrollbar {
      padding: 0;
      height: 50vh;
    }
  }
</style>
